package com.lagou.controller;

import com.lagou.pojo.AuthCode;
import com.lagou.service.AuthCodeService;
import com.lagou.service.EmailService;
import com.lagou.util.RandomUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    private AuthCodeService authCodeService;

    @Reference
    private EmailService emailService;

    /**
     * ⽣成验证码并发送到对应邮箱
     * @param email
     * @return
     */
    @GetMapping("/create/{email}")
    public boolean createCode(@PathVariable("email") String email){
        try {
            String randomNum = RandomUtil.createRandomNum();
            Date date = new Date();

            Calendar instance = Calendar.getInstance();
            instance.setTime(date);
            instance.add(Calendar.MINUTE,10);
            Date expireDate = instance.getTime();

            AuthCode authCode = new AuthCode();
            authCode.setCreatetime(date);
            authCode.setExpiretime(expireDate);
            authCode.setEmail(email);
            authCode.setCode(randomNum);

            authCodeService.save(authCode);

            emailService.sendEmail(email, randomNum);


        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 校验验证码是否正确，0正确 1错误 2超时
     * @param email
     * @param code
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validateCode(@PathVariable("email") String email,
                                @PathVariable("code") String code){
        AuthCode authCode = authCodeService.findOneByEmailAndCode(email, code);
        if(authCode == null)
            return 1;
        long currentTimeMillis = System.currentTimeMillis();
        long time = authCode.getExpiretime().getTime();
        if(currentTimeMillis > time)
            return 2;
        return 0;
    }

}
